﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using wdwp.Desktop.widgetLib.CommonTypes;


namespace wdwp.Desktop.Launcher
{
    /// <summary>
    /// 위젯들을 관리하는 GUI 인터페이스 
    /// </summary>
    public partial class WidgetControlForm : Form
    {   

        WidgetLauncher m_launcher;
        int m_procSelIndex;



        //생성자///////////////////////////////////////////////

        public WidgetControlForm(WidgetLauncher launcher)
        {            
            InitializeComponent();
            
            m_launcher = launcher;
        }
        
        //Public function///////////////////////////////////////////////
        


        //Helper function///////////////////////////////////////////////

        private void LogMsg(string Msg)
        {            
            listLog.Items.Add("MSG :" + Msg);                            
        }

        private void LogErr(string Msg)
        {
            listLog.Items.Add("ERR :" + Msg);
            MessageBox.Show("에러발생 : " + Msg, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); 
        }

        private void LogNull(string Msg)
        {            
        }

        //이벤트 핸들러/////////////////////////////////////////////// 

        private void widgetControlForm_Load(object sender, EventArgs e)
        {
            try
            {
                //메세지 핸들러
                WidgetLauncher.SrcLoadingCompleted += new WidgetLauncher.LauncherEventHandler(widgetLauncher_srcLoadingComplete);
                WidgetLauncher.ProcListChanged += new WidgetLauncher.LauncherEventHandler(widgetLauncher_procListChanged);
                WidgetLauncher.Error += new WidgetLauncher.LogMsgHandler(LogErr);
                WidgetLauncher.Message += new WidgetLauncher.LogMsgHandler(LogMsg);                
                
                //매니저 구동
                m_launcher.InitManager();

                tmrUpdate.Start();
               
                //위젯 호스팅 창을 활성화 합니다. 
                //m_wndLauncherHost = new widgetHostForm();
                //m_wndLauncherHost.TransparencyKey = Color.Magenta;
                //m_wndLauncherHost.Show();
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc.ToString());
                LogErr(exc.Source + exc.Message + exc.TargetSite);

                //초기에 문제가 발생할 경우 아무것도 실행 못함 
                btnRunSelWidget.Enabled = false;
                btnKillSelWidget.Enabled = false;
                listProcs.Enabled = false;
                listSrcs.Enabled = false;                    
            }
        }

        private void btnRunSelWidget_Click(object sender, EventArgs e)
        {
            try
            {
                if (listSrcs.SelectedItems.Count > 0)
                {
                    ListViewItem viewItem = listSrcs.SelectedItems[0];
                    string Name = viewItem.SubItems[0].Text;
                    string Type = viewItem.SubItems[1].Text;

                    m_launcher.RunNewWidget(Name, Type);
                }
                else
                {
                    MessageBox.Show("실행할 위젯을 선택해 주세요!.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                
            }
            catch (Exception exc)
            {
                LogErr(exc.Source + exc.Message + exc.TargetSite);
            }
        }

        private void btnKillSelWidget_Click(object sender, EventArgs e)
        {
            try
            {
                if (listProcs.SelectedItems.Count > 0)
                {
                    ListViewItem viewItem = listProcs.SelectedItems[0];
                    string Name = viewItem.SubItems[0].Text;
                    string Type = viewItem.SubItems[1].Text;
                    string Pid = viewItem.SubItems[2].Text;

                    m_launcher.KillWidget(int.Parse(Pid));
                }
                else
                {
                    MessageBox.Show("종료할 위젯을 선택해 주세요", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);                        
                }
            }
            catch (Exception exc)
            {
                LogErr(exc.Source + exc.Message + exc.TargetSite);
            }           

        }


        private void widgetLauncher_srcLoadingComplete(object sender, WidgetEventArgs e)
        {
            ArrayList arSrcs = e.Content as ArrayList;

            foreach( sWidgetInfo aSrc in arSrcs )
            {
                string[] subItems = { aSrc.Name, aSrc.Type, aSrc.FullHTMLUri };                
                ListViewItem newItem = new ListViewItem( subItems );
                listSrcs.Items.Add(newItem);                                
            }

        }


        private void widgetLauncher_procListChanged(object sender, WidgetEventArgs e)
        {
            if(listProcs.SelectedItems.Count > 0)
                m_procSelIndex = listProcs.SelectedItems[0].Index;

            WidgetProcManager procMngr = sender as WidgetProcManager;
            ArrayList arProcs = procMngr.ProcessList as ArrayList;
            
            listProcs.Items.Clear();

            foreach (sWidgetProc aProc in arProcs)
            {
                string[] subItems = { aProc.SrcInfo.Name, aProc.SrcInfo.Type, aProc.procId.ToString() };
                ListViewItem newItem = new ListViewItem(subItems);
                listProcs.Items.Add(newItem);
            }         

            //if(listProcs.SelectedItems.Count > 0)
                
        }

        private void widgetControlForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {   
                m_launcher.ExitLauncher();
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc.ToString());
                MessageBox.Show("정상적으로 종료할수가 없습니다. \n 예외 : "
                                + exc.Message + " at " + exc.Source + exc.StackTrace, 
                                this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void KillWidget_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listProcs.SelectedItems.Count > 0)
            {
                btnKillSelWidget_Click(btnKillSelWidget, new EventArgs());
            }
        }

        private void HideShow_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listProcs.SelectedItems.Count > 0)
            {

            }
        }

        private void tmrUpdate_Tick(object sender, EventArgs e)
        {
            m_launcher.Refresh();            
        }

        private void ctMstrp_ClientControl_Opening(object sender, CancelEventArgs e)
        {
            tmrUpdate.Stop();
        }

        private void ctMstrp_ClientControl_Closed(object sender, ToolStripDropDownClosedEventArgs e)
        {
            tmrUpdate.Start();
        }

        private void ctMstrp_ClientControl_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            tmrUpdate.Stop();
        }          
    }
}
